<template>
	<view class="become-matchmaker">
		<!-- 提示弹窗 -->
		<u-modal v-model="showTips" :show-cancel-button="true" confirm-text="我已知晓" cancel-text="取消" title="温馨提示"
			@confirm="confirmTips">
			<view class="modal-content">
				<text>成为红娘后：\n</text>
				<text>- 不会在首页展示\n</text>
				<text>- 开启"我的团队"功能\n</text>
				<text>- 开启"我的奖励"功能\n</text>
				<text>- 需遵守平台红娘行为规范</text>
			</view>
		</u-modal>

		<!-- 申请表单 -->
		<view class="application-form" v-if="!showTips">
			<view class="section-title">基本信息</view>
			<view class="form-section">
				<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm">
					<u-form-item label="真实姓名" prop="real_name" labelWidth="150rpx" :borderBottom="true">
						<u--input v-model="form.real_name" border="none" placeholder="请填写与身份证一致的姓名"></u--input>
					</u-form-item>

					<u-form-item label="手机号码" prop="phone" labelWidth="150rpx" :borderBottom="true">
						<u--input v-model="form.phone" border="none" placeholder="请填写常用手机号" type="number"></u--input>
					</u-form-item>

					<u-form-item label="微信" prop="wechat" labelWidth="150rpx" :borderBottom="true">
						<u--input v-model="form.wechat" border="none" placeholder="请填写微信号"></u--input>
					</u-form-item>

					<u-form-item label="QQ" prop="qq" labelWidth="150rpx" :borderBottom="true">
						<u--input v-model="form.qq" border="none" placeholder="请填写QQ号"></u--input>
					</u-form-item>

					<u-form-item label="从业年限" prop="experience" labelWidth="150rpx" :borderBottom="true">
						<u--input v-model="form.experience" border="none" placeholder="请填写从业年限"
							type="number"></u--input>
					</u-form-item>

					<u-form-item label="成功案例数" prop="success_cases" labelWidth="150rpx" :borderBottom="true">
						<u--input v-model="form.success_cases" border="none" placeholder="请填写成功撮合的情侣数量"
							type="number"></u--input>
					</u-form-item>
				</u--form>
			</view>

			<view class="section-title">身份证明（必传）</view>
			<view class="upload-section">
				<view class="upload-item">
					<text>身份证正面</text>
					<u-upload :fileList="idCardFrontList" @afterRead="afterRead" @delete="deletePic" name="idCardFront"
						:maxCount="1" uploadIcon="camera-fill" :previewFullImage="true"></u-upload>
				</view>

				<view class="upload-item">
					<text>身份证反面</text>
					<u-upload :fileList="idCardBackList" @afterRead="afterRead" @delete="deletePic" name="idCardBack"
						:maxCount="1" uploadIcon="camera-fill" :previewFullImage="true"></u-upload>
				</view>

				<view class="upload-item">
					<text>手持身份证半身照</text>
					<u-upload :fileList="idCardHandheldList" @afterRead="afterRead" @delete="deletePic"
						name="idCardHandheld" :maxCount="1" uploadIcon="camera-fill"
						:previewFullImage="true"></u-upload>
				</view>
			</view>

			<view class="section-title">资格证书（选传）</view>
			<view class="upload-section">
				<view class="upload-item">
					<text>婚姻顾问资格证书</text>
					<u-upload :fileList="qualificationCertList" @afterRead="afterRead" @delete="deletePic"
						name="qualificationCert" :maxCount="1" uploadIcon="plus" :previewFullImage="true"></u-upload>
				</view>

				<view class="upload-item">
					<text>心理咨询师证书</text>
					<u-upload :fileList="psychologyCertList" @afterRead="afterRead" @delete="deletePic"
						name="psychologyCert" :maxCount="1" uploadIcon="plus" :previewFullImage="true"></u-upload>
				</view>

				<view class="upload-item">
					<text>最高学历证书</text>
					<u-upload :fileList="educationCertList" @afterRead="afterRead" @delete="deletePic"
						name="educationCert" :maxCount="1" uploadIcon="plus" :previewFullImage="true"></u-upload>
				</view>

				<view class="upload-item">
					<text>曾任职机构证明</text>
					<u-upload :fileList="employmentProofList" @afterRead="afterRead" @delete="deletePic"
						name="employmentProof" :maxCount="1" uploadIcon="plus" :previewFullImage="true"></u-upload>
				</view>
			</view>

			<view class="section-title">案例与问题回答</view>
			<view class="form-section">
				<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm">
					<u-form-item label="最成功案例描述" prop="best_case" labelWidth="150rpx" :borderBottom="true">
						<u--textarea v-model="form.best_case" placeholder="请描述您最成功的撮合案例" height="100"></u--textarea>
					</u-form-item>

					<u-form-item label="父母反对处理方案" prop="parent_oppose_solution" labelWidth="150rpx"
						:borderBottom="true">
						<u--textarea v-model="form.parent_oppose_solution" placeholder="当男方父母反对时您的处理方案"
							height="100"></u--textarea>
					</u-form-item>

					<u-form-item label="隐瞒婚史处理方案" prop="hidden_marriage_solution" labelWidth="150rpx"
						:borderBottom="true">
						<u--textarea v-model="form.hidden_marriage_solution" placeholder="发现会员隐瞒婚史该如何处理"
							height="100"></u--textarea>
					</u-form-item>
				</u--form>
			</view>

			<view class="submit-btn">
				<button @click="submitApplication" :disabled="submitting">
					{{ submitting ? '提交中...' : '提交申请' }}
				</button>
			</view>
		</view>
	</view>
</template>

<script>
import { BASE_URL } from '@/util/api';
import { cleanUrl, completeUrl } from '@/util/urlHelper';

export default {
	data() {
		return {
			showTips: false, // 控制提示弹窗显示
			submitting: false, // 防止重复提交

			// 上传文件列表
			idCardFrontList: [],
			idCardBackList: [],
			idCardHandheldList: [],
			qualificationCertList: [],
			psychologyCertList: [],
			educationCertList: [],
			employmentProofList: [],

			// 表单数据
			form: {
				real_name: '',
				phone: '',
				wechat: '',
				qq: '',
				experience: '',
				success_cases: '',
				best_case: '',
				parent_oppose_solution: '',
				hidden_marriage_solution: '',
			},

			// 表单验证规则
			rules: {
				real_name: {
					type: 'string',
					required: true,
					message: '请填写真实姓名',
					trigger: ['blur', 'change']
				},
				phone: {
					type: 'string',
					required: true,
					pattern: /^1[3-9]\d{9}$/,
					message: '请填写正确的手机号',
					trigger: ['blur', 'change']
				},
				wechat: {
					validator: (rule, value, callback) => {
						if (!value && !this.form.qq) {
							callback(new Error('请至少填写微信或QQ'));
						} else {
							callback();
						}
					},
					trigger: ['blur', 'change']
				},
				qq: {
					validator: (rule, value, callback) => {
						if (!value && !this.form.wechat) {
							callback(new Error('请至少填写微信或QQ'));
						} else {
							callback();
						}
					},
					trigger: ['blur', 'change']
				},
				experience: {
					type: 'number',
					required: true,
					message: '请填写从业年限',
					trigger: ['blur', 'change']
				},
				success_cases: {
					type: 'number',
					required: true,
					message: '请填写成功案例数量',
					trigger: ['blur', 'change']
				},
				//   best_case: {
				// 	type: 'string',
				// 	required: true,
				// 	message: '请描述最成功案例',
				// 	trigger: ['blur', 'change']
				//   },
				//   parent_oppose_solution: {
				// 	type: 'string',
				// 	required: true,
				// 	message: '请回答父母反对时的处理方案',
				// 	trigger: ['blur', 'change']
				//   },
				//   hidden_marriage_solution: {
				// 	type: 'string',
				// 	required: true,
				// 	message: '请回答发现隐瞒婚史时的处理方案',
				// 	trigger: ['blur', 'change']
				//   }
			}
		};
	},
	methods: {
		// 确认提示
		confirmTips() {
			this.showTips = false;
		},

		// 图片上传相关方法 (与示例代码类似)
		deletePic(event) {
			this[`${event.name}List`].splice(event.index, 1);
		},

		async afterRead(event) {
			let lists = [].concat(event.file);
			let fileListLen = this[`${event.name}List`].length;

			lists.map((item) => {
				this[`${event.name}List`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});

			for (let i = 0; i < lists.length; i++) {
				try {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`${event.name}List`][fileListLen];
					const completeUrlResult = completeUrl(result);

					this[`${event.name}List`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: completeUrlResult
					}));

					fileListLen++;
				} catch (error) {
					console.error('上传失败:', error);
					this[`${event.name}List`][fileListLen].status = 'failed';
					this[`${event.name}List`][fileListLen].message = '上传失败';
				}
			}
		},

		uploadFilePromise(filePath) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: BASE_URL + '/index/api/upload',
					filePath: filePath,
					name: 'file',
					success: (uploadRes) => {
						try {
							const res = JSON.parse(uploadRes.data);
							if (res.code === 200) {
								let url = res.url || res.path;
								if (url.startsWith('http')) {
									url = cleanUrl(url);
								}
								resolve(url);
							} else {
								reject(new Error(res.message || '上传失败'));
							}
						} catch (e) {
							reject(new Error('解析响应数据失败'));
						}
					},
					fail: (error) => {
						reject(error);
					}
				});
			});
		},

		// 提交申请
		async submitApplication() {
			try {
				// 验证必传图片
				if (this.idCardFrontList.length === 0 || this.idCardBackList.length === 0 || this.idCardHandheldList.length === 0) {
					uni.showToast({
						title: '请上传完整的身份证明照片',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 验证表单
				await this.$refs.uForm.validate();

				this.submitting = true;

				const launchFlag = uni.getStorageSync('my_info');
				const submitData = {
					uid: launchFlag.id,
					...this.form,
					id_card_front: cleanUrl(this.idCardFrontList[0].url),
					id_card_back: cleanUrl(this.idCardBackList[0].url),
					id_card_handheld: cleanUrl(this.idCardHandheldList[0].url),
					qualification_cert: this.qualificationCertList[0] ? cleanUrl(this.qualificationCertList[0].url) : '',
					psychology_cert: this.psychologyCertList[0] ? cleanUrl(this.psychologyCertList[0].url) : '',
					education_cert: this.educationCertList[0] ? cleanUrl(this.educationCertList[0].url) : '',
					employment_proof: this.employmentProofList[0] ? cleanUrl(this.employmentProofList[0].url) : '',
				};

				const res = await this.$myRuquest({
					url: '/index/api/apply_matchmaker',
					method: 'POST',
					data: submitData,
				});

				if (res.data.code === 200) {
					uni.showToast({
						title: '申请提交成功',
						icon: 'success',
						duration: 2000
					});

					setTimeout(() => {
						uni.switchTab({
							url: '/pages/my/my'
						});
					}, 2000);
				} else {
					uni.showToast({
						title: res.data.info || '提交失败',
						icon: 'none',
						duration: 2000
					});
				}
			} catch (error) {
				console.error('提交失败:', error);
				uni.showToast({
					title: '提交失败，请检查表单',
					icon: 'none',
					duration: 2000
				});
			} finally {
				this.submitting = false;
			}
		}
	}
};
</script>

<style lang="scss">
.become-matchmaker {
	padding: 20rpx;
	background-color: #eb9dc824;

	.modal-content {
		padding: 20rpx;
		line-height: 1.8;
		font-size: 28rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin: 30rpx 0 20rpx;
		color: #333;
	}

	.form-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 0 20rpx;
		margin-bottom: 20rpx;
	}

	.upload-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;

		.upload-item {
			margin-bottom: 30rpx;

			text {
				display: block;
				margin-bottom: 15rpx;
				font-size: 28rpx;
				color: #666;
			}
		}
	}

	.submit-btn {
		margin: 40rpx 0;

		button {
			background-color: #f14399;
			color: #fff;
			border-radius: 50rpx;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 32rpx;

			&[disabled] {
				background-color: #e6434066;
			}
		}
	}
}
</style>